package com.yklx.youke.controller;

import com.yklx.youke.entity.Classroom;
import com.yklx.youke.entity.Session;
import com.yklx.youke.service.ClassroomService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/classrooms")
@CrossOrigin(origins = "*")
public class ClassroomController {

    private final ClassroomService classroomService;

    public ClassroomController(ClassroomService classroomService) {
        this.classroomService = classroomService;
    }

    @GetMapping("/{sessionId}")
    public ResponseEntity<?> getClassroomBySessionId(@PathVariable UUID sessionId) {
        try {
            Classroom classroom = classroomService.getClassroomBySessionId(sessionId);
            if (classroom != null) {
                // Prepare response with classroom info and WebRTC configuration
                Map<String, Object> response = Map.of(
                    "classroom", classroom,
                    "webrtcConfig", Map.of(
                        "iceServers", new String[]{"stun:stun.l.google.com:19302"},
                        "offerOptions", Map.of("offerToReceiveAudio", true, "offerToReceiveVideo", true)
                    ),
                    "accessCode", classroom.getAccessCode()
                );
                return ResponseEntity.ok(response);
            } else {
                // If classroom doesn't exist, create one for the session
                Session session = new Session(); // This would actually come from a service
                Classroom newClassroom = classroomService.createClassroomForSession(session);
                
                Map<String, Object> response = Map.of(
                    "classroom", newClassroom,
                    "webrtcConfig", Map.of(
                        "iceServers", new String[]{"stun:stun.l.google.com:19302"},
                        "offerOptions", Map.of("offerToReceiveAudio", true, "offerToReceiveVideo", true)
                    ),
                    "accessCode", newClassroom.getAccessCode()
                );
                return ResponseEntity.ok(response);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    @PostMapping("/{sessionId}/record")
    public ResponseEntity<?> startStopRecording(@PathVariable UUID sessionId, @RequestBody Map<String, String> request) {
        String action = request.get("action"); // "start" or "stop"
        
        try {
            Map<String, Object> response = classroomService.startStopRecording(sessionId, action);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
}